package org.luxor.cloud.gateway.component.security;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author yanxinming
 */
public class SecurityUtils {

    /**
     * 匿名用户
     */
    public static UserSubject ANONYMUS;

    static {
        ANONYMUS = new UserSubject();
        ANONYMUS.setRealName("匿名用户");
        ANONYMUS.setUsername(SecurityConstants.ANONYMOUS);
        ANONYMUS.setPassword(StringUtils.EMPTY);
        ANONYMUS.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
        ANONYMUS.setEnabled(true);
        ANONYMUS.setAccountNonLocked(true);
        ANONYMUS.setAccountNonExpired(true);
        ANONYMUS.setCredentialsNonExpired(true);
    }

    /**
     * 返回唯一登陆账号
     *
     * @return
     */
    public static String getUsername() {
        return getUser().getUsername();
    }

    /**
     * 返回登陆者真实姓名
     *
     * @return
     */
    public static String getRealName() {
        return getUser().getRealName();
    }

    /**
     * 返回登陆者主体对象
     *
     * @return
     */
    public static UserSubject getUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            return ANONYMUS;
        }
        return (UserSubject) context.getAuthentication().getPrincipal();
    }
}
